package rexsee.dialog;

import rexsee.core.browser.Browser;
import rexsee.core.lang.RexseeLanguage;
import rexsee.core.style.RexseeDrawable;
import rexsee.core.utilities.Utilities;
import rexsee.core.widget.DivDialog;
import rexsee.dialog.ImageMultiTouchListener.OnImageDragedOverThresholdListener;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.widget.ImageView;

public class ImageDialog extends DivDialog {

	public final ImageView mView;
	private Runnable mClickCallback = null;
	private final OnImageDragedOverThresholdListener mDragListener;

	public ImageDialog(Browser browser, String url, String style, OnImageDragedOverThresholdListener dragListener) {
		super(browser, null, style);
		mDragListener = dragListener;
		mView = new ImageView(mContext);
		mView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
		this.addChild(mView);
		setImage(url);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mBrowser.menu.isOptionsMenuOpen) {
				((Activity) mContext).closeOptionsMenu();
				return true;
			} else {
				if (styleSheet.window_cancelable.equalsIgnoreCase("true")) dismiss();
			}
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			((Activity) mContext).openOptionsMenu();
		} else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_FOCUS) {
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
		} else {
		}
		return false;
	}

	@Override
	protected void onClick(DialogInterface dialog) {
		if (mClickCallback != null) {
			mClickCallback.run();
		}
	}

	public void setImage(final String url) {
		if (url == null || url.trim().equals("")) {
			((Activity) mContext).runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mView.setImageDrawable(null);
				}
			});
			return;
		}
		mBrowser.progressDialog.show(RexseeLanguage.PROGRESS_ONGOING);
		new Thread() {
			@Override
			public void run() {
				final Drawable drawable = RexseeDrawable.getDrawable(mBrowser, url);
				mBrowser.progressDialog.hide();
				if (drawable == null) {
					mBrowser.exception("ImageDialog", "Null drawable.");
				} else {
					((Activity) mContext).runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mView.setImageDrawable(drawable);
						}
					});
				}
			}
		}.start();
	}
	public void setClickCallback(Runnable clickCallback) {
		mClickCallback = clickCallback;
	}
	@Override
	public void setStyle(String style) {
		super.setStyle(style);
		if (styleSheet.event_multitouch.equalsIgnoreCase("true")) {
			mView.setOnTouchListener(new ImageMultiTouchListener(mView, Utilities.getInt(styleSheet.distance_threshold, 0), mDragListener));
		} else {
			mView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
			mView.setOnTouchListener(null);
		}
	}

}
